package tcu.iot.mqttupdate.controller;

import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import tcu.iot.mqttupdate.entity.MQTTConnect;
import tcu.iot.mqttupdate.entity.MQTTQuery;
import tcu.iot.mqttupdate.entity.R;
import tcu.iot.mqttupdate.entity.SubscribeDevice;
import tcu.iot.mqttupdate.service.MQTTService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * MQTT客户端控制器
 * 实现所有和MQTT相关功能
 * 连接，订阅，发送，返回数据
 */
@RestController
@RequestMapping("/mqtt")
@CrossOrigin
public class MQTTController {

    @Resource
    private MQTTService mqttService;

    /**
     * 连接MQTT接口，接收HOST，USERNAME，PASSWORD
     */
    @PostMapping(value = "/connect")
    @PostConstruct
    public R InitMQTT() {
        return mqttService.initMQTT();
    }

    /**
     * 订阅设备接口，接收deviceName，订阅相应设备数据
     * 访问此接口后，会传回最近一条数据，直接上传数据库
     * 若数据库没有相应设备数据表，则自动创建
     */
    @SneakyThrows
    @PostMapping(value = "/subscribe")
    public R SubscribeDevice() {
        return mqttService.subscribe();
    }

    /**
     * MQTT publish功能实现。
     * 当成功连接MQTT后，可以给任意已订阅设备发送任意消息
     */
//    @PostMapping(value = "/publish")
//    public R PublishMessage(MQTTPublish mqttPublish) {
//        return mqttService.publish(mqttPublish);
//    }

//    /**
//     * 根据传入的subscribe返回所有数据
//     */
//    @PostMapping(value = "/data")
//    public R getMQTTData(SubscribeDevice subscribeDevice) {
//        return mqttService.getData(subscribeDevice);
//    }

    @GetMapping(value = "/disconnect")
    public R MQTTDisconnect(){
        return mqttService.disconnect();
    }

    @GetMapping(value = "delete")
    public R DeleteData(){
        return mqttService.DeleteData();
    }
}
